<template>
    <div class="container">
        <div class="header-wrapper">
            <van-nav-bar title="更改头像" left-text="返回" left-arrow @click-left="onClickLeft">
                <template #right>
                    <van-button type="success" @click="onSave">保存</van-button>
                </template>
            </van-nav-bar>
        </div>
        <van-field name="uploader" label="修改头像" class="uploader-field">
            <template #input>
                <van-uploader v-model="upload_img" :after-read="afterRead" :max-count="1" />
            </template>
        </van-field>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import * as qiniu from 'qiniu-js';
import { useRouter } from 'vue-router';
import http from '../http';
import { useUserStore } from '@/stores/counter';
const userStore = useUserStore();
const router = useRouter();
const upload_img = ref([]);
const qiniu_img = ref('');
let token = ref('');

const getQiniuToken = () => {
    http.get('/escort/qiniu_token').then(res => {
        if (res.status === 200) {
            token.value = res.data.token
        }
    }).catch(err => {
        console.log(err);
    })
};
const onSave = () => {
    const userphone = userStore.phone;
    const imgUrl = qiniu_img.value;
    console.log('<<<<<<', userphone, imgUrl);
    http.put(`/escort/searchescort/${userphone}/`, {
        phone: userStore.phone,
        avatar: imgUrl,
    }).then(res => {
        console.log('用户头像更新成功', res.data);
        router.push({
            path: '/mypage',
            query: {
                new_avatar: imgUrl,
            }
        })
    }).catch(err => {
        console.log('用户头像更新失败', err);
    });
}

const afterRead = (file) => {
    http.post('/escort/qiniuimgurl/', {
        key: file.file.name
    }).then(res => {
        if (res.status === 200) {
            console.log('图片地址成功', res.data.download_url);
            qiniu_img.value = res.data.download_url;
        }
    }).catch(err => {
        console.log("失败", err);
    })
    try {
        const config = {
            useCdnDomain: true, //使用 cdn 加速域名
        };
        const observable = qiniu.upload(file.file, file.file.name, token.value, config);
        const observer = {
            next(res) {
                console.log('上传进度', res.total.percent);
            },
            error(err) {
                console.log('文件上传失败', err);
            },
            complete(res) {
                console.log('文件上传成功', res);
            },
        };
        const subscription = observable.subscribe(observer); // 上传开始
        subscription.unsubscribe(); // 上传取消
    } catch (err) {
        console.log('获取上传凭证失败', err);
    }
};

onMounted(() => {
    getQiniuToken();
});

const onClickLeft = () => history.back();
</script>
<style scoped>
.container {
    height: 100vh;
    background-color: #faf8f8;
}

.header-wrapper {
    width: 100%;
}
</style>